package licode.unisop.auth.domain.user.service;

import cn.hutool.core.util.StrUtil;
import licode.unisop.auth.client.info.CheckContextIn;
import licode.unisop.auth.client.info.IdentityContextIn;
import licode.unisop.auth.client.info.IdentityIn;
import licode.unisop.auth.client.info.UserIdFindIn;
import licode.unisop.auth.domain.user.gateway.AuthorGateway;
import licode.unisop.auth.domain.user.gateway.UserGateway;
import licode.unisop.auth.exception.AuthErrorCode;
import licode.unisop.provider.info.SiUserId;
import licode.unisop.provider.vo.SiUser;
import licode.unisop.types.dp.UserState;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * 处理用户相关的业务逻辑
 *
 * @author licode
 */
@Service
public class UserInfoService {
    @Resource
    private UserGateway userGateway;

    @Resource
    private AuthorGateway authorGateway;

    public void validUser(SiUser user, String realmId) {
        if (null == user || StrUtil.isBlank(user.getId())) {
            throw AuthErrorCode.USER_NOT_EXIST.buildThrow();
        }

        if (!UserState.ACTIVATED.getState().equals(user.getState())) {
            throw AuthErrorCode.USER_WRONG_STATE.buildThrow();
        }

        if (null == user.getRealmId() || !user.getRealmId().equals(realmId)) {
            throw AuthErrorCode.USER_INVALID_ACCOUNT.buildThrow();
        }
    }

    public SiUser checkUser(UserIdFindIn findIn) {
        SiUser user = userGateway.findUser(findIn);
        validUser(user, findIn.getRealmId());
        return user;
    }

    /**
     * 通过登录信息校验用户，同时返回用户信息
     *
     * @param context 登录信息
     * @return 返回认证码
     */
    public SiUser checkUser(CheckContextIn context) {
        // 1. 先根据账号信息查找到对应用户
        SiUser user = userGateway.findUser(context.getAccount());

        validUser(user, context.getAccount().getRealmId());

        // 2.获取用户的认证信息
        IdentityIn identity = userGateway.findIdentity(UserIdFindIn
                .builder()
                .realmId(context.getAccount().getRealmId())
                .userId(user.getId())
                .authType(context.getAuth().getAuthType())
                .build());

        if (null == identity) {
            AuthErrorCode.USER_INVALID_AUTH.throwBy();
        }

        // 3. 开始认证用户
        if (!authorGateway.checkUser(IdentityContextIn
                .builder()
                .user(user)
                .realmId(user.getRealmId())
                .platformId(context.getPlatformId())
                .exist(identity)
                .target(context.getAuth())
                .build())) {
            AuthErrorCode.USER_CHECK_CREDENTIAL_FAIL.throwBy();
        }

        return user;
    }
}
